//
//  QFScreenshotMan.swift
//  QFImageMaskDemo
//
//  Created by Anakin chen on 2020/3/13.
//  Copyright © 2020 QF Network Technology. All rights reserved.
//

import UIKit
import Foundation
import Photos
import CoreGraphics

class QFScreenshotMan: NSObject {
    
    static let shared = QFScreenshotMan()
    var shareImage: UIImage?
    var screenshotV: UIView?
    
    override init() {
        super.init()
        self.addNotification()
    }
    
    // MARK: Private
    
    private func addNotification() {
        // [iOS 获取系统截屏事件](https://www.jianshu.com/p/a535d167ffcc)
        NotificationCenter.default.addObserver(self, selector: #selector(userDidTakeScreenshot(notification:)), name: UIApplication.userDidTakeScreenshotNotification, object: nil)
    }
    
    private func showScreenshot() {
        guard let data = dataWithScreenshotInPNGFormat() else {
            print("showScreenshot data 失败")
            return
        }
        guard let image = UIImage(data: data) else {
            print("showScreenshot image 失败")
            return
        }
        let info = "\(CFAbsoluteTimeGetCurrent())\r\n -《静夜思》- 李白\r\n 床前明月光，疑是地上霜。举头望明月，低头思故乡。"
        if let i = QFLSBMan.encode(image: image, info: info) {
            shareImage = i
            print("加密完成，加密内容：\(info)")
        }
        else {
            print("加密失败")
            return
        }
        /* 加密后将图片先以缓存本地再获取出来进行分享和保存相册，才有效。否则会被加密数据会丢失，然后分享，目前测试是 QQ 和 钉钉 才不会丢失加密数据，微信会丢失
         */
        if !toPng() {
            print("showScreenshot toPng 失败")
            return
        }
        
        let view = UIView(frame: UIScreen.main.bounds)
        view.backgroundColor = UIColor.clear
        if let vc = UIApplication.shared.keyWindow?.rootViewController { vc.view.addSubview(view)
        }
        else {
            UIApplication.shared.keyWindow?.addSubview(view)
        }
        screenshotV = view
        
        let bgV = UIView(frame: view.bounds)
        bgV.backgroundColor = UIColor(white: 0, alpha: 0.3)
        view.addSubview(bgV)
        
        let y: CGFloat = 130
        let b: CGFloat = 130
        let h = view.bounds.size.height - y - b
        let w = h * (shareImage!.size.width / shareImage!.size.height)
        let x = (view.bounds.size.width - w) / 2
        let iv = UIImageView(frame: CGRect(x: x, y: y, width: w, height: h))
        iv.image = shareImage!
        view.addSubview(iv)
        
        let wb: CGFloat = iv.frame.size.width
        let hb: CGFloat = 30
        let bottomV = UIView(frame: CGRect(x: iv.frame.origin.x, y: iv.frame.origin.y + iv.frame.size.height - hb, width: wb, height: hb))
        bottomV.backgroundColor = UIColor.clear
        view.addSubview(bottomV)
        
        let bottomgbV = UIView(frame: bottomV.bounds)
        bottomgbV.backgroundColor = UIColor(white: 0, alpha: 0.6)
        bottomV.addSubview(bottomgbV)
        
        var xx: CGFloat = 0
        let wbb = wb / 2
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.backgroundColor = UIColor.clear
        leftBtn.frame = CGRect(x: xx, y: 0, width: wbb, height: hb)
        leftBtn.setTitle("保存", for: .normal)
        leftBtn.setTitleColor(UIColor.black, for: .normal)
        leftBtn.addTarget(self, action: #selector(saveImageAction(sender:)), for: .touchUpInside)
        bottomV.addSubview(leftBtn)
        
        xx += wbb
        
        let rightBtn = UIButton(type: .custom)
        rightBtn.backgroundColor = UIColor.clear
        rightBtn.frame = CGRect(x: xx, y: 0, width: wbb, height: hb)
        rightBtn.setTitle("分享", for: .normal)
        rightBtn.setTitleColor(UIColor.black, for: .normal)
        rightBtn.addTarget(self, action: #selector(shareImageAction(sender:)), for: .touchUpInside)
        bottomV.addSubview(rightBtn)
        
        let closeBtn = UIButton(type: .custom)
        closeBtn.backgroundColor = UIColor.black
        closeBtn.frame = CGRect(x: view.frame.size.width - 60, y: 60, width: 30, height: 30)
        closeBtn.layer.masksToBounds = true
        closeBtn.layer.cornerRadius = 15
        closeBtn.setTitle("X", for: .normal)
        closeBtn.setTitleColor(UIColor.white, for: .normal)
        closeBtn.addTarget(self, action: #selector(closeAction(sender:)), for: .touchUpInside)
        view.addSubview(closeBtn)
    }
    
    private func save4Photo() {
        guard let image = shareImage else {
            return
        }
        var createdAssetID: String?
        PHPhotoLibrary.requestAuthorization { (stauts) in
            if stauts == PHAuthorizationStatus.authorized {
                do {
                    try PHPhotoLibrary.shared().performChangesAndWait {
                    createdAssetID = PHAssetChangeRequest.creationRequestForAsset(from: image).placeholderForCreatedAsset?.localIdentifier ?? nil
                    }
                    if let aid = createdAssetID {
                        PHAsset.fetchAssets(withLocalIdentifiers: [aid], options: nil)
                        DispatchQueue.main.async {
                            if let vc = UIApplication.shared.keyWindow?.rootViewController {
                                let alert = UIAlertController(title: "提示", message: "已保存到相册", preferredStyle: .alert)
                                let cancel = UIAlertAction(title: "确定", style: .cancel) { (UIAlertAction) in
                                }
                                alert.addAction(cancel)
                                vc.present(alert, animated: true, completion: nil)
                            }
                        }
                    }
                }
                catch {
                }
            }
        }
    }
    
    private func save4Caches() {
        let manager = FileManager.default
        let url = manager.urls(for: .cachesDirectory, in: .userDomainMask).first! as NSURL
        let path = url.appendingPathComponent("QFShotScreenImage.png")
        if let data = shareImage!.pngData() {
            do {
                try data.write(to: path!)

                let dd = try Data(contentsOf: path!)
                let i = UIImage(data: dd, scale: UIScreen.main.scale)
                shareImage = i
            }
            catch {

            }
        }
        guard let image = shareImage else {
            return
        }
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
        if let vc = UIApplication.shared.keyWindow?.rootViewController {
            let alert = UIAlertController(title: "提示", message: "已保存到相册，如没有请检查是否开启权限", preferredStyle: .alert)
            let cancel = UIAlertAction(title: "确定", style: .cancel) { (UIAlertAction) in
            }
            alert.addAction(cancel)
            vc.present(alert, animated: true, completion: nil)
        }
    }
    
    private func dataWithScreenshotInPNGFormat() -> Data? {
        var size = UIScreen.main.bounds.size
        let orientation = UIApplication.shared.statusBarOrientation
        if orientation == .landscapeLeft || orientation == .landscapeRight {
            size = CGSize(width: size.height, height: size.width)
        }
        
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        if let context = UIGraphicsGetCurrentContext() {
            for window in UIApplication.shared.windows {
                context.saveGState()
                context.concatenate(window.transform)
                if orientation == .landscapeLeft {
                    context.rotate(by: .pi / 2)
                    context.translateBy(x: 0, y: -size.width)
                }
                else if orientation == .landscapeRight {
                    context.rotate(by: -(.pi / 2))
                    context.translateBy(x: -size.height, y: 0)
                }
                else if orientation == .portraitUpsideDown {
                    context.rotate(by: .pi / 2)
                    context.translateBy(x: -size.width, y: -size.height)
                }
                if window.responds(to: #selector(window.drawHierarchy(in:afterScreenUpdates:))) {
                    window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
                }
                else {
                    window.layer.render(in: context)
                }
                context.restoreGState()
            }
            
            let text = "QFScreenshot" as NSString
            let p = CGPoint(x: 20, y: 160)
            text.draw(at: p, withAttributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor(white: 0.5, alpha: 1)])
                
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            
            return image?.pngData()
        }
        return nil
    }
    
    private func toPng() -> Bool {
        guard let image = shareImage else {
            return false
        }
        let manager = FileManager.default
        let url = manager.urls(for: .cachesDirectory, in: .userDomainMask).first! as NSURL
        let path = url.appendingPathComponent("QFShotScreenImage.png")
        if let data = image.pngData() {
            do {
                try data.write(to: path!)

                let dd = try Data(contentsOf: path!)
                let i = UIImage(data: dd, scale: UIScreen.main.scale)
                shareImage = i
                return true
            }
            catch {
                
            }
        }
        return false
    }
    
    // MARK: Action
    
    @objc func userDidTakeScreenshot(notification: Notification) {
        showScreenshot()
    }
    
    @objc func saveImageAction(sender: UIButton) {
        save4Photo()
    }
    
    @objc func shareImageAction(sender: UIButton) {
        guard let i = shareImage else {
            return
        }
        let activityVC = UIActivityViewController(activityItems: [i], applicationActivities: nil)
        activityVC.isModalInPopover = true
        if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
            rootVC.present(activityVC, animated: true) {
                DispatchQueue.main.async {
                    if let vc = UIApplication.shared.keyWindow?.rootViewController {
                        let alert = UIAlertController(title: "提示", message: "分享操作已完成", preferredStyle: .alert)
                        let cancel = UIAlertAction(title: "确定", style: .cancel) { (UIAlertAction) in
                        }
                        alert.addAction(cancel)
                        vc.present(alert, animated: true, completion: nil)
                    }
                }
            }
        }
    }
    
    @objc func closeAction(sender: UIButton) {
        if let v = self.screenshotV {
            v.removeFromSuperview()
        }
    }
}
